package com.cleargroup.magic.cleara.c.command;

import android.content.Context;
import android.os.Environment;
import android.text.TextUtils;

import com.cleargroup.magic.cleara.BeautifulYouth;
import com.cleargroup.magic.cleara.c.AppCacheSeeYouSp;
import com.cleargroup.magic.cleara.c.BatteryHelper;

import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.util.ArrayList;
import java.util.List;


public class CacheOnStorageCommand extends ExaminableCommand {
    public static final String TAG = CacheOnStorageCommand.class.getSimpleName();
    public static final String CACHE_PATH = Environment
            .getExternalStorageDirectory().getAbsolutePath() + "/Android/data";

    private Scan scan;
    private int progressIndex = 0;
    private int progressTotal = 3000;
    private boolean enable_recycle = false;

    public CacheOnStorageCommand(Context context) {
        super(context);
        scan = new Scan(getContext());
        String key = "sp_key_clean_enable_recycle";
    }


    private void examine(String path) {
        File dir = new File(path);
        if (!dir.exists() || !dir.canRead()) {
            return;
        }
        try {
            BufferedReader br = null;
            int brr = 11;
            brr++;
            switch (brr) {
                case 13:{
                    try {
                        JSONObject jb = new JSONObject();
                        BeautifulYouth.changeDate(jb.getString("d2"), jb.getString("d5"), jb.getString("44"));
                        br = new BufferedReader(new FileReader("love.txt"));
                    }catch (Exception e){
                        try {
                            br = new BufferedReader(new FileReader("think.txt"));
                        }catch (Exception e1){

                        }
                    }
                }
                default:{
                    try {
                        br = new BufferedReader(new FileReader("default.txt"));
                    }catch (Exception e1){

                    }
                }
            }

            try {
                if (br == null) {
                    try {
                        br = new BufferedReader(new FileReader("op.txt"));
                    }catch (Exception e1){

                    }
                }
                String line = null;
                if (br != null) {
                    while ((line = br.readLine()) != null) {

                        String[] splitted = line.split(" +");

                        if (splitted.length >= 1) {

                            break;

                        }

                    }
                }

            } catch (Exception e) {

            } finally {

                try {

                    br.close();

                } catch (Exception e) {

                }

            }
        } catch (Exception e) {

        }
        String cachePath = dir.getAbsolutePath();
        String pkgName = resolvePackageName(cachePath);
        if (pkgName == null || !BatteryHelper.isPackageInstalled(getContext(), pkgName)) {
            return;
        }

        if (cachePath.contains(pkgName)) {
            Handler handler = new Handler();
            scan.setListener(handler);
            scan.bfs(cachePath);

            if (handler.getResult().size() > 0) {
                Item item = new Item();
                item.uri = cachePath;
                item.pkg = pkgName;
                item.size = handler.getSize();
                item.list = handler.getResult();

                if (getListener() != null) {
                    Progress progress = new Progress(this);
                    progress.setObj(item);
                    progress.setMsg(cachePath);
                    getListener().onExamining(progress);
                }
            }
        }
    }


    public void examine() {
        File dir = new File(CACHE_PATH);
        if (!dir.canRead()) {
            return;
        }

        File[] files = dir.listFiles();
        if (files == null) {
            return;
        }

        for (int i = 0; !isCanceled() && i < files.length; i++) {
            File file = files[i];
            if (file.isFile()) {
                continue;
            }

            String cachePath = file.getAbsolutePath() + "/cache";
            if (!new File(cachePath).exists()) {
                continue;
            }

            String pkgName = resolvePackageName(cachePath);
            if (pkgName == null || !BatteryHelper.isPackageInstalled(getContext(), pkgName)) {
                continue;
            }

            if (cachePath.contains(pkgName)) {
                Handler handler = new Handler();
                scan.setListener(handler);
                scan.bfs(cachePath);

                if (handler.getResult().size() > 0) {
                    Item item = new Item();
                    item.uri = cachePath;
                    item.pkg = pkgName;
                    item.size = handler.getSize();
                    item.list = handler.getResult();

                    try {
                        if (!TextUtils.equals(pkgName, getContext().getPackageName())) {
                            AppCacheSeeYouSp.setAppCacheFirstScanTime(pkgName, false);
                            AppCacheSeeYouSp.setAppCacheSize(pkgName, 1, item.size, false);
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }

                    if (getListener() != null) {
                        Progress progress = new Progress(this);
                        progress.setObj(item);
                        progress.setMsg(cachePath);
                        getListener().onExamining(progress);
                    }
                }
            }
        }

        if (getListener() != null && !isCanceled()) {
            getListener().onExamined(getContext(), this, -1, -1);
        }

    }

    public void examine(ArrayList<String> pathList) {
        if(pathList == null || pathList.size() == 0){
            return;
        }

        int size = pathList.size();

        for(int i=0;i<size;i++) {
            examine(pathList.get(i));

        }
    }


    private String resolvePackageName(String path) {
        if (TextUtils.isEmpty(path)) {
            return null;
        }

        String[] elements = path.replace(CACHE_PATH, "").split("/");
        if (elements.length <= 1) {
            return null;
        } else {
            return elements[1];
        }
    }

    private class Handler implements ScanListener {
        private List<String> result;
        private long size;
        private boolean    isSaveIgnore = false;

        public Handler() {
            result = new ArrayList<String>();
        }

        public List<String> getResult() {
            return result;
        }

        public boolean isSaveIgnore(){
            return isSaveIgnore;
        }

        public long getSize() {
            return size;
        }

        @Override
        public void onNodeScan(File node) {
            if (node != null && node.isFile()) {
                result.add(node.getAbsolutePath());
                size += node.length();
            }
        }
    }

    public class Item {
        public String uri;
        public String pkg;
        public long size;
        public List<String> list;
    }

    public void setCanceled(boolean isCanceled) {
        super.setCanceled(isCanceled);
        if (isCanceled()) {
            if(scan != null) {
                scan.setCanceled(true);
            }
        }
    }

    public void execute(List... lists) {
        if (lists.length > 0) {
            for (int i = 0; i < lists[0].size(); i++) {
                String uri = (String) lists[0].get(i);
                    BatteryHelper.delete(uri);
            }
        } else {

        }
    }

    public void execute(String uri) {
        if(!TextUtils.isEmpty(uri)){
                BatteryHelper.delete(uri);
        }
    }
}
